package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("=== 无缓冲channel ===")
	unbuffered()

	fmt.Println("\n=== 有缓冲channel ===")
	buffered()
}

func unbuffered() {
	ch := make(chan int) // 无缓冲

	go func() {
		for i := 1; i <= 2; i++ {
			fmt.Printf("无缓冲-发送: %d\n", i)
			ch <- i // 会阻塞，直到有人接收
			fmt.Printf("无缓冲-发送完成: %d\n", i)
		}
		close(ch)
	}()

	time.Sleep(100 * time.Millisecond) // 让发送者先开始
	for num := range ch {
		fmt.Printf("无缓冲-接收: %d\n", num)
		time.Sleep(500 * time.Millisecond)
	}
}

func buffered() {
	ch := make(chan int, 3) // 有缓冲，容量3

	go func() {
		for i := 1; i <= 5; i++ {
			fmt.Printf("有缓冲-发送: %d\n", i)
			ch <- i // 前3个不会阻塞
			fmt.Printf("有缓冲-发送完成: %d\n", i)
		}
		close(ch)
	}()

	time.Sleep(100 * time.Millisecond)
	for num := range ch {
		fmt.Printf("有缓冲-接收: %d\n", num)
		time.Sleep(500 * time.Millisecond)
	}
}
